// 测评列表状态管理
let reviewsState = {
    reviews: [],
    filters: {
        sortBy: 'latest',
        gameType: 'all',
        search: ''
    },
    pagination: {
        currentPage: 1,
        totalPages: 1,
        pageSize: 10
    },
    stats: {
        totalReviews: 0,
        hotGame: '',
        topRatedGame: ''
    }
};

// 测评数据结构
const reviewData = {
    // 游戏基础信息
    gameInfo: {
        id: null,
        title: '',
        cover: '',
        genre: '',
        publisher: ''
    },
    // 测评内容
    review: {
        rating: 0,
        content: '',
        playTime: 0,  // 游戏时长（小时）
        platform: '',  // 游玩平台
        purchaseType: '', // 购买类型（正版、租赁等）
        pros: [],     // 优点标签
        cons: [],     // 缺点标签
        tags: [],     // 其他标签
        screenshots: [], // 游戏截图
        videoUrl: '',   // 视频链接
        recommendLevel: '', // 推荐等级
    },
    // 元数据
    metadata: {
        userId: '',
        username: '',
        createTime: '',
        updateTime: '',
        status: 'draft', // draft, published, deleted
        visibility: 'public', // public, private, friends
    },
    // 统计数据
    stats: {
        likes: 0,
        comments: 0,
        shares: 0,
        views: 0
    }
};

// 显示写测评表单
function showReviewForm() {
    const modal = document.getElementById('reviewModal');
    if (!modal) return;
    
    modal.style.display = 'flex';
    document.body.style.overflow = 'hidden'; // 防止背景滚动
    
    // 重置表单
    resetReviewForm();
    
    // 初始化字数统计
    const textarea = modal.querySelector('textarea');
    if (textarea) {
        updateWordCount(textarea);
    }
}

// 隐藏写测评表单
function hideReviewForm() {
    const modal = document.getElementById('reviewModal');
    if (!modal) return;
    
    modal.style.display = 'none';
    document.body.style.overflow = ''; // 恢复背景滚动
    
    // 重置表单
    resetReviewForm();
}

// 重置表单
function resetReviewForm() {
    const form = document.querySelector('.review-form');
    if (!form) return;
    
    // 重置选择框
    const selects = form.querySelectorAll('select');
    selects.forEach(select => {
        select.value = '';
        select.disabled = false;
    });
    
    // 重置评分
    const stars = form.querySelectorAll('.rating-input i');
    stars.forEach(star => {
        star.classList.remove('fas');
        star.classList.add('far');
    });
    
    // 重置文本
    const textarea = form.querySelector('textarea');
    if (textarea) {
        textarea.value = '';
        updateWordCount(textarea);
    }
    
    // 重置评分文本
    const ratingText = form.querySelector('.rating-text');
    if (ratingText) {
        ratingText.textContent = '请选择评分';
    }
    
    // 清除错误提示
    const errorMessages = form.querySelectorAll('.error-message');
    errorMessages.forEach(msg => msg.remove());
}

// 更新字数统计
function updateWordCount(textarea) {
    const wordCount = document.querySelector('.word-count');
    const length = textarea.value.length;
    wordCount.textContent = `${length}/1000`;
    
    if (length < 100) {
        wordCount.style.color = '#ff4444';
    } else {
        wordCount.style.color = '#666';
    }
}

// 更新评分文本
function updateRatingText(rating) {
    const ratingText = document.querySelector('.rating-text');
    const texts = ['很差', '较差', '一般', '不错', '很棒'];
    ratingText.textContent = texts[rating - 1] || '请选择评分';
}

// 初始化测评表单
function initReviewForm() {
    const form = document.querySelector('.review-form');
    if (!form) return;
    
    const textarea = document.querySelector('.review-form textarea');
    if (textarea) {
        textarea.addEventListener('input', () => updateWordCount(textarea));
    }
    
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach(star => {
        star.addEventListener('click', () => {
            const rating = star.dataset.rating;
            updateStars(rating);
            updateRatingText(rating);
        });
        
        star.addEventListener('mouseover', () => {
            const rating = star.dataset.rating;
            previewStars(rating);
        });
        
        star.addEventListener('mouseout', () => {
            const currentRating = document.querySelector('.rating-input .fas')?.dataset.rating;
            previewStars(currentRating || 0);
        });
    });
}

// 预览星星效果
function previewStars(rating) {
    const stars = document.querySelectorAll('.rating-input i');
    stars.forEach((star, index) => {
        if (index < rating) {
            star.classList.remove('far');
            star.classList.add('fas');
        } else {
            star.classList.remove('fas');
            star.classList.add('far');
        }
    });
}

// 更新星星显示
function updateStars(rating) {
    previewStars(rating);
}

// 提交测评
async function submitReview() {
    try {
        // 收集表单数据
        const formData = collectReviewFormData();
        
        // 验证数据
        const validationResult = validateReviewData(formData);
        if (!validationResult.isValid) {
            showError(validationResult.message);
            return;
        }

        // 构建测评数据
        const review = buildReviewData(formData);

        // 上传图片（如果有）
        if (review.review.screenshots.length > 0) {
            const uploadedImages = await uploadImages(review.review.screenshots);
            review.review.screenshots = uploadedImages;
        }

        // 提交测评
        // const response = await fetch('/api/reviews', {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //         'Authorization': `Bearer ${getAuthToken()}`
        //     },
        //     body: JSON.stringify(review)
        // });

        // if (!response.ok) {
        //     throw new Error('提交失败');
        // }

        // const result = await response.json();
        console.log('提交测评:', review);

        // 成功处理
        hideReviewForm();
        showSuccess('测评发布成功！');
        loadReviews();
        loadStats();

    } catch (error) {
        console.error('提交测评失败:', error);
        showError('提交测评失败，请稍后重试');
    }
}

// 收集表单数据
function collectReviewFormData() {
    return {
        gameId: document.getElementById('gameSelect').value,
        rating: document.querySelectorAll('.rating-input .fas').length,
        content: document.querySelector('.review-form textarea').value,
        platform: document.getElementById('platform').value,
        playTime: document.getElementById('playTime').value,
        purchaseType: document.getElementById('purchaseType').value,
        pros: Array.from(document.querySelectorAll('.pros-tags .selected')).map(tag => tag.dataset.tag),
        cons: Array.from(document.querySelectorAll('.cons-tags .selected')).map(tag => tag.dataset.tag),
        tags: Array.from(document.querySelectorAll('.other-tags .selected')).map(tag => tag.dataset.tag),
        screenshots: Array.from(document.getElementById('screenshots').files),
        videoUrl: document.getElementById('videoUrl').value,
        recommendLevel: document.querySelector('input[name="recommend"]:checked').value,
        visibility: document.getElementById('visibility').value
    };
}

// 验证测评数据
function validateReviewData(data) {
    if (!data.gameId) {
        return { isValid: false, message: '请选择游戏' };
    }
    if (!data.rating) {
        return { isValid: false, message: '请选择评分' };
    }
    if (!data.content || data.content.length < 100) {
        return { isValid: false, message: '测评内容不能少于100字' };
    }
    if (data.content.length > 1000) {
        return { isValid: false, message: '测评内容不能超过1000字' };
    }
    if (data.screenshots.length > 5) {
        return { isValid: false, message: '最多上传5张截图' };
    }
    // 更多验证规则...

    return { isValid: true };
}

// 构建测评数据
function buildReviewData(formData) {
    return {
        gameInfo: {
            id: formData.gameId,
            // 其他游戏信息会从后端获取
        },
        review: {
            rating: formData.rating,
            content: formData.content,
            playTime: parseInt(formData.playTime),
            platform: formData.platform,
            purchaseType: formData.purchaseType,
            pros: formData.pros,
            cons: formData.cons,
            tags: formData.tags,
            screenshots: formData.screenshots,
            videoUrl: formData.videoUrl,
            recommendLevel: formData.recommendLevel
        },
        metadata: {
            userId: getCurrentUserId(),
            username: getCurrentUsername(),
            createTime: new Date().toISOString(),
            updateTime: new Date().toISOString(),
            status: 'published',
            visibility: formData.visibility
        },
        stats: {
            likes: 0,
            comments: 0,
            shares: 0,
            views: 0
        }
    };
}

// 上传图片
async function uploadImages(files) {
    const uploadedUrls = [];
    for (const file of files) {
        const formData = new FormData();
        formData.append('image', file);

        // const response = await fetch('/api/upload/image', {
        //     method: 'POST',
        //     body: formData
        // });
        // const result = await response.json();
        // uploadedUrls.push(result.url);

        // 模拟上传
        uploadedUrls.push(URL.createObjectURL(file));
    }
    return uploadedUrls;
}

// 获取当前用户信息
function getCurrentUserId() {
    // 从登录状态获取
    return 'currentUserId';
}

function getCurrentUsername() {
    // 从登录状态获取
    return '当前用户';
}

// 显示成功提示
function showSuccess(message) {
    // 实现成功提示UI
    console.log('成功:', message);
}

// 初始化页面
document.addEventListener('DOMContentLoaded', () => {
    initReviewForm();
    initFilterListeners();
    initSearch();
    loadReviews();
    loadStats();
});

// 加载统计数据
async function loadStats() {
    try {
        // API调用示例
        // const response = await fetch('/api/reviews/stats');
        // const data = await response.json();
        
        // 模拟API响应
        const data = {
            totalReviews: 1234,
            hotGame: "塞尔达传说",
            topRatedGame: "艾尔登法环"
        };
        
        updateStats(data);
    } catch (error) {
        console.error('加载统计数据失败:', error);
    }
}

// 更新统计面板
function updateStats(data) {
    reviewsState.stats = data;
    document.querySelector('.stat-number').textContent = data.totalReviews;
    document.querySelector('.stat-text:nth-of-type(1)').textContent = data.hotGame;
    document.querySelector('.stat-text:nth-of-type(2)').textContent = data.topRatedGame;
}

// 加载测评列表
async function loadReviews() {
    try {
        const params = new URLSearchParams({
            page: reviewsState.pagination.currentPage,
            pageSize: reviewsState.pagination.pageSize,
            sortBy: reviewsState.filters.sortBy,
            gameType: reviewsState.filters.gameType,
            search: reviewsState.filters.search
        });

        // API调用示例
        // const response = await fetch(`/api/reviews?${params}`);
        // const data = await response.json();
        
        // 模拟API响应
        const data = {
            reviews: [
                {
                    id: 1,
                    user: {
                        id: 1,
                        name: "用户名",
                        avatar: "https://via.placeholder.com/40"
                    },
                    game: {
                        id: 1,
                        title: "艾尔登法环",
                        cover: "https://via.placeholder.com/120",
                        genre: "动作角色扮演",
                        publisher: "FromSoftware"
                    },
                    rating: 4.5,
                    content: "这是一款非常优秀的游戏，开放世界设计令人���叹...",
                    date: "2024-03-15",
                    likes: 128,
                    comments: 36
                }
            ],
            totalPages: 10
        };

        reviewsState.reviews = data.reviews;
        reviewsState.pagination.totalPages = data.totalPages;
        
        renderReviews();
        updatePagination();
    } catch (error) {
        console.error('加载测评数据失败:', error);
        showError('加载测评数据失败，请稍后重试');
    }
}

// 渲染测评列表
function renderReviews() {
    const reviewsList = document.querySelector('.reviews-list');
    reviewsList.innerHTML = reviewsState.reviews.map(review => createReviewCard(review)).join('');
}

// 创建测评卡片
function createReviewCard(review) {
    return `
        <div class="review-card" data-review-id="${review.id}">
            <div class="review-header">
                <div class="user-info">
                    <img src="${review.user.avatar}" alt="${review.user.name}" class="user-avatar">
                    <div class="user-details">
                        <h4>${review.user.name}</h4>
                        <span class="review-date">${review.date}</span>
                    </div>
                </div>
                <div class="game-rating">
                    <div class="stars">${generateStars(review.rating)}</div>
                    <span class="rating-score">${review.rating}</span>
                </div>
            </div>
            <div class="review-content">
                <div class="game-info">
                    <img src="${review.game.cover}" alt="${review.game.title}" class="game-cover">
                    <div class="game-details">
                        <h3>${review.game.title}</h3>
                        <span class="game-meta">${review.game.genre} | ${review.game.publisher}</span>
                    </div>
                </div>
                <p class="review-text">${review.content}</p>
                <div class="review-actions">
                    <button class="action-btn like-btn" onclick="handleLike(${review.id})">
                        <i class="far fa-thumbs-up"></i>
                        <span>${review.likes}</span>
                    </button>
                    <button class="action-btn comment-btn" onclick="handleComment(${review.id})">
                        <i class="far fa-comment"></i>
                        <span>${review.comments}</span>
                    </button>
                    <button class="action-btn share-btn" onclick="handleShare(${review.id})">
                        <i class="far fa-share-square"></i>
                    </button>
                </div>
            </div>
        </div>
    `;
}

// 处理点赞
async function handleLike(reviewId) {
    try {
        // 检查用户是否登录
        if (!isLoggedIn()) {
            showLoginModal();
            return;
        }

        const likeBtn = document.querySelector(`[data-review-id="${reviewId}"] .like-btn`);
        const likeCount = likeBtn.querySelector('span');
        const isLiked = likeBtn.classList.contains('liked');

        // API调用示例
        // const response = await fetch(`/api/reviews/${reviewId}/like`, {
        //     method: isLiked ? 'DELETE' : 'POST',
        //     headers: {
        //         'Authorization': `Bearer ${getAuthToken()}`
        //     }
        // });
        // const result = await response.json();

        // 更新UI
        if (isLiked) {
            likeBtn.classList.remove('liked');
            likeCount.textContent = parseInt(likeCount.textContent) - 1;
        } else {
            likeBtn.classList.add('liked');
            likeCount.textContent = parseInt(likeCount.textContent) + 1;
        }

        // 添加动画效果
        likeBtn.querySelector('i').classList.add('animate-like');
        setTimeout(() => {
            likeBtn.querySelector('i').classList.remove('animate-like');
        }, 300);

    } catch (error) {
        console.error('点赞失败:', error);
        showError('操作失败，请稍后重试');
    }
}

// 处理评论
function handleComment(reviewId) {
    // 检查用户是否登录
    if (!isLoggedIn()) {
        showLoginModal();
        return;
    }

    // 显示评论框
    const reviewCard = document.querySelector(`[data-review-id="${reviewId}"]`);
    const commentSection = reviewCard.querySelector('.comment-section');
    
    if (!commentSection) {
        // 创建评论区域
        const newCommentSection = createCommentSection(reviewId);
        reviewCard.querySelector('.review-content').appendChild(newCommentSection);
    } else {
        // 切换评论区域显示状态
        commentSection.classList.toggle('hidden');
    }
}

// 创建评论区域
function createCommentSection(reviewId) {
    const section = document.createElement('div');
    section.className = 'comment-section';
    section.innerHTML = `
        <div class="comments-list">
            <!-- 评论列表将通过 loadComments 动态加载 -->
        </div>
        <div class="comment-form">
            <textarea placeholder="写下你的评论..." rows="3"></textarea>
            <button onclick="submitComment(${reviewId})">发表评论</button>
        </div>
    `;

    // 加载评论
    loadComments(reviewId);
    return section;
}

// 加载评论
async function loadComments(reviewId) {
    try {
        // API调用示例
        // const response = await fetch(`/api/reviews/${reviewId}/comments`);
        // const comments = await response.json();

        // 模拟评论数据
        const comments = [
            {
                id: 1,
                userId: 'user1',
                username: '用户A',
                avatar: 'https://via.placeholder.com/30',
                content: '这个游戏确实不错！',
                createTime: '2024-03-15 14:30'
            }
        ];

        renderComments(reviewId, comments);
    } catch (error) {
        console.error('加载评论失败:', error);
    }
}

// 渲染评论
function renderComments(reviewId, comments) {
    const commentsList = document.querySelector(`[data-review-id="${reviewId}"] .comments-list`);
    commentsList.innerHTML = comments.map(comment => `
        <div class="comment-item" data-comment-id="${comment.id}">
            <img src="${comment.avatar}" alt="${comment.username}" class="comment-avatar">
            <div class="comment-content">
                <div class="comment-header">
                    <span class="comment-username">${comment.username}</span>
                    <span class="comment-time">${comment.createTime}</span>
                </div>
                <p>${comment.content}</p>
            </div>
        </div>
    `).join('');
}

// 提交评论
async function submitComment(reviewId) {
    const commentForm = document.querySelector(`[data-review-id="${reviewId}"] .comment-form`);
    const textarea = commentForm.querySelector('textarea');
    const content = textarea.value.trim();

    if (!content) {
        showError('请输入评论内容');
        return;
    }

    try {
        // API调用示例
        // const response = await fetch(`/api/reviews/${reviewId}/comments`, {
        //     method: 'POST',
        //     headers: {
        //         'Content-Type': 'application/json',
        //         'Authorization': `Bearer ${getAuthToken()}`
        //     },
        //     body: JSON.stringify({ content })
        // });
        // const result = await response.json();

        // 清空输入框
        textarea.value = '';

        // 重新加载评论
        loadComments(reviewId);

        // 更新评论数
        const commentBtn = document.querySelector(`[data-review-id="${reviewId}"] .comment-btn span`);
        commentBtn.textContent = parseInt(commentBtn.textContent) + 1;

    } catch (error) {
        console.error('提交评论失败:', error);
        showError('评论失败，请稍后重试');
    }
}

// 更新分页UI
function updatePagination() {
    const { currentPage, totalPages } = reviewsState.pagination;
    const pagination = document.querySelector('.pagination .page-numbers');
    
    let pages = [];
    if (totalPages <= 5) {
        pages = Array.from({ length: totalPages }, (_, i) => i + 1);
    } else {
        if (currentPage <= 3) {
            pages = [1, 2, 3, 4, '...', totalPages];
        } else if (currentPage >= totalPages - 2) {
            pages = [1, '...', totalPages - 3, totalPages - 2, totalPages - 1, totalPages];
        } else {
            pages = [1, '...', currentPage - 1, currentPage, currentPage + 1, '...', totalPages];
        }
    }

    pagination.innerHTML = pages.map(page => {
        if (page === '...') {
            return '<span class="page-dots">...</span>';
        }
        return `
            <button class="${page === currentPage ? 'active' : ''}" 
                    data-page="${page}">${page}</button>
        `;
    }).join('');

    // 更新上一页/下一页按钮状态
    const prevBtn = document.querySelector('.prev-page');
    const nextBtn = document.querySelector('.next-page');
    prevBtn.disabled = currentPage === 1;
    nextBtn.disabled = currentPage === totalPages;
}

// 初始化分页事件
function initPagination() {
    const pagination = document.querySelector('.pagination');
    pagination.addEventListener('click', (e) => {
        const target = e.target;
        
        // 处理数字页码按钮
        if (target.matches('[data-page]')) {
            const page = parseInt(target.dataset.page);
            if (page !== reviewsState.pagination.currentPage) {
                reviewsState.pagination.currentPage = page;
                loadReviews();
            }
        }
        
        // 处理上一页按钮
        if (target.closest('.prev-page') && reviewsState.pagination.currentPage > 1) {
            reviewsState.pagination.currentPage--;
            loadReviews();
        }
        
        // 处理下一页按钮
        if (target.closest('.next-page') && 
            reviewsState.pagination.currentPage < reviewsState.pagination.totalPages) {
            reviewsState.pagination.currentPage++;
            loadReviews();
        }
    });
}

// 显示错误提示
function showError(message, element) {
    // 移除已有的错误提示
    const existingError = element?.parentElement.querySelector('.error-message');
    if (existingError) {
        existingError.remove();
    }
    
    // 创建错误提示
    const errorDiv = document.createElement('div');
    errorDiv.className = 'error-message';
    errorDiv.textContent = message;
    
    if (element) {
        // 显示在特定元素下方
        element.parentElement.appendChild(errorDiv);
    } else {
        // 显示全局错误提示
        const toast = document.createElement('div');
        toast.className = 'toast error';
        toast.textContent = message;
        document.body.appendChild(toast);
        
        // 3秒后自动消失
        setTimeout(() => {
            toast.remove();
        }, 3000);
    }
}

// 其他函数保持不变... 